package com.pptv.service;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;

import com.pptv.entity.ProgramEntity;
import com.pptv.util.HttpRequestUtils;

public class ExcelService {
	
	private static final org.apache.log4j.Logger logger = Logger.getLogger(ExcelService.class);
	private static Map<Integer,String> prevueMap = new HashMap<Integer, String>();
	
	static{
		prevueMap.put(0, "抢先");
		prevueMap.put(1, "正片");
		prevueMap.put(2, "预告");
	}
	
	public static void main(String[] args) {
		long startTime = System.currentTimeMillis();
		new ExcelService().exportMultiSheet();
		long endTime = System.currentTimeMillis();
		double time = (endTime-startTime)/1000;
		System.out.println("导出VST数据结束,总共花费："+time+"/s");
	}
	
	public void exportMultiSheet(){
		logger.info("------------开始导出数据-------------");
		FileOutputStream fileOut = null; 
		Workbook workbook = new HSSFWorkbook();
		int[] channel_id = {1,2,3,4,5,8};
		String[] channel_name = {"电影","电视剧","动漫","综艺","纪录片","少儿"};
		for(int i = 0;i < channel_id.length;i++){
			long startTime = System.currentTimeMillis();
			logger.info("------------开始导出"+channel_name[i]+"频道数据--------");
			//第一页响应结果
			JSONObject firResResult = HttpRequestUtils.httpGet("http://api.cp33.ott.cibntv.net/api3.0/videolist?topID="+channel_id[i]+"&pageNo=1");
			JSONArray firVideoList = firResResult.getJSONArray("data");
			int totalPages = (Integer) firResResult.getJSONObject("info").get("totalPages");
			ProgramEntity entity;
			List<ProgramEntity> entityList = new ArrayList<ProgramEntity>();
			for(int k = 1;k <= totalPages;k++){
				JSONObject resResult = new JSONObject();
				if(k == 1){
					resResult = firResResult;
				}else{
					resResult = HttpRequestUtils.httpGet("http://api.cp33.ott.cibntv.net/api3.0/videolist?topID="+channel_id[i]+"&pageNo="+k);
				}
				JSONArray videoList = resResult.getJSONArray("data");
				for(int j = 0;j < videoList.size();j++){
					entity = new ProgramEntity();
					entity.setTitle(videoList.getJSONObject(j).get("title").toString());
					entity.setVip(videoList.getJSONObject(j).get("isAllVip").equals(true)?"是":"否");
					int prevue = (Integer) videoList.getJSONObject(j).get("prevue");
					entity.setPrevue(prevue<2 ? (prevueMap.get(prevue)!=null?prevueMap.get(prevue):prevue+"") : "会员影片");
					entityList.add(entity);
				}
			}
			try {
				ExcelService.writeFcPeakWeekToExcel("VST",entityList,workbook,channel_name[i],i);
			} catch (IOException e) {
				e.printStackTrace();
			}
			long endTime = System.currentTimeMillis();
			logger.info("结束导出"+channel_name[i]+"频道数据");
			logger.info("导出"+channel_name[i]+"频道数据花费："+(endTime-startTime));
		}
	    try {
			fileOut = new FileOutputStream("D:/vst_video.xls");
			// 写入excel文件   
			workbook.write(fileOut);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
	}
	
	public static void writeFcPeakWeekToExcel(String title,List<?> list,Workbook wb,String sheetName,int sheetIndex) throws IOException {
		try{
			Sheet s = wb.createSheet();
			s.setDefaultColumnWidth(20);  
			wb.setSheetName(sheetIndex, sheetName);
			//Label labelCF = null;
			CellStyle cs = wb.createCellStyle();
			Font font = wb.createFont();
			font.setBoldweight(Font.BOLDWEIGHT_BOLD);
			cs.setFont(font);
			
			//创建第一行
			Row r = s.createRow(0);//第一行
			Cell c = r.createCell(0);//第一列
			c.setCellStyle(cs);//样式
			// 定字段名称
			String arrTitle[] ={"标题","是否是vip影片","影片属性"};
			for (int i = 0; i < 3; i++) {
				c = r.createCell(i);
				c.setCellStyle(cs);
				c.setCellValue(arrTitle[i]);
			}
			
			//从第三行开始写内容
			int rowNum = 1;
			r = s.createRow(rowNum);
			for (int i = 0; i < list.size(); i++) {
				ProgramEntity obj = (ProgramEntity) list.get(i);
				
				c = r.createCell(0);
				c.setCellStyle(cs);
				c.setCellValue(obj.getTitle());
				
				c = r.createCell(1);
				c.setCellStyle(cs);
				c.setCellValue(obj.getVip());
				
				c = r.createCell(2);
				c.setCellStyle(cs);
				c.setCellValue(obj.getPrevue());
				
				rowNum++;
				r = s.createRow(rowNum);
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}	
	}
	
	public void exportExcel(){
		FileOutputStream fileOut = null;  
		List<Map<String, String>> list = new ArrayList<Map<String,String>>();
		Map<String, String> map;
	    for (int i = 0; i < 10; i++) {
	        map = new HashMap<String, String>();
	        map.put("title", "1" + i);
	        map.put("vip", "2" + i);
	        map.put("prevue", "3" + i);
	        list.add(map);
	    }
		HSSFWorkbook workbook = (HSSFWorkbook) ExcelExportUtil.exportExcel(new ExportParams("2412312", "测试", "测试"), ProgramEntity.class, list);
		try {
			fileOut = new FileOutputStream("D:/测试Excel.xls");
			// 写入excel文件   
			workbook.write(fileOut);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	public void exportExcelByTemplate(){
			List list = new ArrayList<String>();
		 	TemplateExportParams params = new TemplateExportParams();
		    params.setHeadingRows(2);
		    params.setHeadingStartRow(2);
		    Map<String,Object> map = new HashMap<String, Object>();
		    map.put("year", "2013");
		    map.put("sunCourses", list.size());
		    Map<String,Object> obj = new HashMap<String, Object>();
		    map.put("obj", obj);
		    obj.put("name", list.size());
		    params.setTemplateUrl("org/jeecgframework/poi/excel/doc/exportTemp.xls");
		    Workbook book = ExcelExportUtil.exportExcel(params, ProgramEntity.class, list, map);
	}
	
	public void exportExcelByMap(){
		List<Map<String, String>> result = new ArrayList<Map<String, String>>();
		FileOutputStream fileOut = null; 
		List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
	    entity.add(new ExcelExportEntity("姓名", "name"));
	    entity.add(new ExcelExportEntity("性别", "sex"));
	 
	    List<Map<String, String>> list = new ArrayList<Map<String, String>>();
	    Map<String, String> map;
	    for (int i = 0; i < 10; i++) {
	        map = new HashMap<String, String>();
	        map.put("name", "1" + i);
	        map.put("sex", "2" + i);
	        list.add(map);
	    }
	    HSSFWorkbook workbook = (HSSFWorkbook) ExcelExportUtil.exportExcel(new ExportParams("测试","1"), entity, list);
	    try {
			fileOut = new FileOutputStream("D:/测试Excel.xls");
			// 写入excel文件   
			workbook.write(fileOut);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}   
	}
	
}
